package com.ficus.road.maintain.websocket;

import cn.hutool.core.collection.CollectionUtil;
import com.ficus.road.maintain.core.model.FrameDTO;
import com.ficus.road.maintain.core.model.digitalTwin.LaneInfo;
import com.ficus.road.maintain.ditalTwin.service.DigitalAssetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;

@ServerEndpoint(value = "/ws/replay/{carId}/{uuid}")
@Service
@Slf4j
public class WebSocketReplayManager extends BaseWebSocketManager {

    @Autowired
    DigitalAssetService digitalAssetService;
    /**
     * 建立连接
     * 连接成功后，服务器的回调函数
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(@PathParam("carId") String carId, @PathParam("uuid") String uuid, Session session) {
        log.info("Video: WebSocketReplayManager new session：{}, car:{}, uuid:{}", session.getId(), carId, uuid);
        synchronized (sessions) {
            //回放的时候是根据uuid来存session，一个uuid只对应一个session,因为不同终端的回放需要互不影响
            sessions.computeIfAbsent(uuid, k -> new ArrayList<>()).add(session);
            increaseSession(uuid, session.getId());
        }
    }


    @Override
    public void increaseSession(String uuid, String sessionId) {
        log.info("WebSocketReplayManager increaseSession..., uuid = {}, sessionId = {}", uuid, sessionId);
//        LoadSsfFileProcessor.playFlag.get().add(uuid);
    }

    @Override
    public void decreaseSession(String uuid, String sessionId) {
        sessions.remove(uuid);
        videoService.stopReplayVideo(uuid);
    }

    @Override
    protected void setExtensionAttr(FrameDTO frameDTO) {
        if (frameDTO!= null && CollectionUtil.isNotEmpty(frameDTO.getAssets())) {
            frameDTO.getAssets().stream().forEach(asset -> {
                asset.setMapId(digitalAssetService.getMapIdByTrackId(asset.getTrackId()));
                LaneInfo laneInfo = digitalAssetService.getLaneInfo(asset.getTimestamp());
                asset.setLaneInfo(laneInfo);
            });
        }
    }
}